import React from "react"
import Hello from "./Hello";


// 评论代码
class Comment extends React.Component {

    state = {
        comments :[],
        //评论人
        userName : '',
        userContent:''
    }
    handeForm = (e) => {
        const {name,value} = e.target
        this.setState({
            [name]:value
        })
    }
    addComment = () => {
        const {comments,userName,userContent} = this.state
        if(userName.trim() === '' || userContent.trim() === '') {
            alert("请输入评论人和评论内容")
            return
        }
        const newComment = [{id:Math.random(),name:userName,content:userContent},...comments]
        this.setState({
            comments: newComment,
            userName: "",
            userContent: ""
        })
        console.log(newComment)
    }
    renderList() {
        return this.state.comments.length === 0 ? <div className="no-comment">暂无评论,快去评论吧～</div> :
            <ul>
                {
                    this.state.comments.map(item=>(
                        <li key={item.id}>
                            <h3>{item.name}</h3>
                            <p>{item.content}</p>
                        </li>
                    ))}
            </ul>
    }
    render() {
        const {userName,userContent} = this.state
        return (
            <div className="app">
                <div>
                    <input className="user" type="text" placeholder="请输入评论人" value={userName} name="userName"
                    onChange={this.handeForm}
                    />
                    <br/>
                    <textarea className="content" cols="30" rows="10" placeholder="请输入评论" value={userContent} name="userContent"
                              onChange={this.handeForm}
                    />
                    <br/>
                    <button onClick={this.addComment}>发表评论</button>
                </div>
                {this.renderList()}


        </div>
        );
    }
}
export default Comment
